const { sequelize, DataTypes } = require('../config/database');

const Comment = sequelize.define('Comment', {
  id: {
    type: DataTypes.INTEGER,
    primaryKey: true,
    autoIncrement: true
  },
  
  content: {
    type: DataTypes.STRING(500),
    allowNull: false,
    validate: {
      notEmpty: true,
      len: [1, 500]
    }
  },
  
  images: {
    type: DataTypes.JSON
  },
  
  // 评论状态
  status: {
    type: DataTypes.ENUM('active', 'deleted'),
    defaultValue: 'active'
  }
  
}, {
  tableName: 'parkpart_comments',  // 修改表名
  timestamps: true,
  paranoid: true,
  indexes: [
    { fields: ['activityId'] },
    { fields: ['userId'] },
    { fields: ['createdAt'] }
  ]
});

// 关联表定义
Comment.associate = (models) => {
  // 评论所属活动
  Comment.belongsTo(models.Activity, {
    foreignKey: 'activityId',
    as: 'activity'
  });
  
  // 评论作者
  Comment.belongsTo(models.User, {
    foreignKey: 'userId',
    as: 'author'
  });
};

// 钩子函数
Comment.beforeCreate(async (comment) => {
  // 设置默认值
  if (!comment.images) comment.images = [];
});

Comment.beforeUpdate(async (comment) => {
  // 确保JSON字段有值
  if (!comment.images) comment.images = [];
});

module.exports = Comment;